#!/usr/bin/env python3
"""
大众点评爬虫 P4 版本 - 延迟管理器
负责智能延迟策略
"""

import time
import random
import logging
from typing import Dict, Any
from pathlib import Path
import sys

# 添加配置路径
sys.path.append(str(Path(__file__).parent.parent))
from config.settings import get_config

logger = logging.getLogger(__name__)

class DelayManager:
    """延迟管理器 - 智能延迟策略"""
    
    def __init__(self):
        config = get_config()
        self.base_delays = config['delays'].copy()
        
        # 延迟统计
        self.stats = {
            'total_delays': 0,
            'total_delay_time': 0,
            'delay_types': {}
        }
        
    def execute_delay(self, delay_type: str, response_time: float = 0, 
                     is_error: bool = False, extra_factor: float = 1.0) -> float:
        """执行智能延迟"""
        
        # 获取基础延迟
        base_delay = self.base_delays.get(delay_type, self.base_delays['normal'])
        
        # 根据响应时间调整
        if response_time > 10:  # 响应慢，减少延迟
            response_factor = 0.8
        elif response_time < 3:  # 响应快，增加延迟
            response_factor = 1.2
        else:
            response_factor = 1.0
        
        # 错误恢复延迟
        if is_error:
            base_delay = self.base_delays['error_recovery']
            response_factor = 1.5
        
        # 计算最终延迟
        final_delay = base_delay * response_factor * extra_factor
        
        # 添加随机性 (±20%)
        random_factor = random.uniform(0.8, 1.2)
        final_delay *= random_factor
        
        # 执行延迟
        logger.info(f"[DELAY_MANAGER] {delay_type} 延迟: {final_delay:.1f}秒")
        time.sleep(final_delay)
        
        # 更新统计
        self.stats['total_delays'] += 1
        self.stats['total_delay_time'] += final_delay
        self.stats['delay_types'][delay_type] = self.stats['delay_types'].get(delay_type, 0) + 1
        
        return final_delay
    
    def city_switch_delay(self, response_time: float = 0) -> float:
        """城市切换延迟"""
        return self.execute_delay('city_switch', response_time)
    
    def category_switch_delay(self, response_time: float = 0) -> float:
        """类别切换延迟"""
        return self.execute_delay('category_switch', response_time)
    
    def page_turn_delay(self, response_time: float = 0, is_empty_page: bool = False) -> float:
        """翻页延迟"""
        extra_factor = 1.3 if is_empty_page else 1.0
        return self.execute_delay('page_turn', response_time, extra_factor=extra_factor)
    
    def error_recovery_delay(self, error_count: int = 1) -> float:
        """错误恢复延迟"""
        extra_factor = min(error_count * 0.5, 3.0)  # 最多3倍延迟
        return self.execute_delay('error_recovery', extra_factor=extra_factor, is_error=True)
    
    def get_delay_stats(self) -> Dict[str, Any]:
        """获取延迟统计"""
        avg_delay = (self.stats['total_delay_time'] / max(self.stats['total_delays'], 1))
        
        return {
            'total_delays': self.stats['total_delays'],
            'total_delay_time': round(self.stats['total_delay_time'], 2),
            'average_delay': round(avg_delay, 2),
            'delay_types': self.stats['delay_types'].copy(),
            'base_delays': self.base_delays.copy()
        }
